
#include "utils.h"
#include "fs/file.h"
#include "fs/path.h"
#include "file_http_reply.h"

using fs::Path;

struct FileHttpReply::Impl {
	fs::File file;
	const MimeTypes &mimetypes;
	fs::Path filename;

	Impl( const MimeTypes & mimetypes_ ): mimetypes( mimetypes_ )
	{
		
	}
};

FileHttpReply::FileHttpReply(const Path &filename, const MimeTypes &mimetypes): 
_pimpl( new Impl(mimetypes) )
{
	_pimpl->filename = filename;
	bool open_flag = _pimpl->file.open( filename.as_string(), fs::FILE_READ );
	if( open_flag )
	{
		status_code( SC_OK );
		headers.set( "Content-Type", _pimpl->mimetypes[ filename.extension() ] );
		headers.set( "Content-Length", itoa(_pimpl->file.size()) );
	} 
	else 
	{
		status_code( SC_NOT_FOUND );
	}

}

FileHttpReply::~FileHttpReply()
{
	delete _pimpl;
}

void FileHttpReply::send_body(sock::ClientSocket &sock)
{
	if( _pimpl->file.isopen()  )
	{
		char buf[1024];
		for( size_t bytes_read = 0; ( bytes_read = _pimpl->file.read( buf, 1024 ) ) > 0; )
		{
			sock.write( buf, bytes_read );
		}
	}
}